import React, { useEffect, useState, useRef } from 'react'
import { message } from 'antd'
import storage from '../utils/storage'
import { useNavigate } from 'react-router-dom'
import 'animate.css';
import './App.scss'
import {
    Form,
    Input,
    Button,
} from 'antd-mobile'
import axios from '../http/axios'
import socket from '../socket';
// import './App.css'
export default function Login() {
    const [messageApi, contextHolder] = message.useMessage()
    //成功提示
    const success = (a) => {

        messageApi.open({
            type: 'success',
            content: a,
        })
    }
    //失败提示
    const error = (a) => {

        messageApi.open({
            type: 'error',
            content: a,
        });
    };
    let nav = useNavigate()
    const videoRef = useRef(null)
    const [faceCheck, setFaceCheck] = useState(false)
    const canvasRef = useRef(null)
    const imageRef = useRef(null)
    const [video, setVideo] = useState()
    const [canvas, setCanvas] = useState()
    // const notification = navigator.mediaDevices
    const [image, setImage] = useState(null)
    const [faceLogin, setFaceLogin] = useState(true)
    const timer = useRef(null) // 定时器
    const [loginMode, setLoginMode] = useState('form') // 登录方式
    useEffect(() => {
        setCanvas(canvasRef.current)
        setVideo(videoRef.current)
        setImage(imageRef.current)
        if (video && faceLogin) {
            // 开启摄像头

            // 获取头像 base64，轮询调登录接口

        }
        if (!faceLogin) {
            timer.current && clearInterval(timer.current)
        }
        return () => {
            timer.current && clearInterval(timer.current)
        }
    }, [videoRef, video, faceLogin, canvas, canvasRef])
    // 打开摄像头
    const openMedia = () => {
        const constraints = {
            video: { width: 50, height: 50 },
            audio: false, // 音频不需要开启
        }
        //获得video摄像头
        if (
            navigator.mediaDevices === undefined ||
            navigator.mediaDevices.getUserMedia === undefined
        ) {
            timer.current && clearInterval(timer.current)
            stopCapture()
            setFaceCheck(false) // 人脸识别失败
            setFaceLogin(false)  // 隐藏人脸识别登录界面
            setLoginMode('form') // 切换登录方式为账号密码
            return
        }
        const promise = navigator?.mediaDevices?.getUserMedia(constraints)
        promise
            .then((mediaStream) => {
                video.srcObject = mediaStream
                video.play()
            }
            )
    }
    //停止摄像机
    const stopCapture = () => {
        if (!video.srcObject) return
        const stream = video.srcObject
        const tracks = stream.getTracks()
        tracks.forEach((track) => {
            track.stop()
        })
    }
    // 获取头像的 base64，轮询调登录接口
    const getPhotoUrl = (() => {
        let num = 0
        timer.current = setInterval(async () => {
            num++
            const ctx = canvas.getContext('2d')

            ctx.drawImage(video, 0, 0, 500, 500)
            // toDataURL  ---  可传入'image/png'---默认, 'image/jpeg'
            const img = canvas.toDataURL() // img 是获取到的base64格式的字符串
            // 这里调接口 login(img) 
            if (num >= 1) {
                clearInterval(timer.current)
                // image.src = image
                let { data: { msg, user_id ,copy} } = await axios.post('/login', { avatar: img })
                video.pause()
                stopCapture()
                success(msg)
                if (msg === '登录成功') {
                    sessionStorage.setItem('token', '123456')
                    sessionStorage.setItem('user_id', user_id)
                    let account = username
                  
                    storage.set('selfInfo', copy)
                 
                    socket.emit('reqLatestPrivateHistory', account)
            
                    socket.emit('saveSocketId', { account })
                    nav('/yinmeng')

                } else {
                    error('登录失败，请重试')
                    setFaceCheck(true)
                }
            }
            setImage(img)
        }, 2000)
    })
    const [flag, setflag] = useState(false)
    // 
    const login = () => {
        openMedia()
        getPhotoUrl()
        setflag(true)
    }
    const [username, setname] = useState('')
    const [password, setpassword] = useState('')
    // 用户密码登录
    const login1 = async () => {
        if (password && username) {
            let { data: { msg, user_id, copy } } = await axios.post('/login', { username, password })
     
            if (msg === '登录成功') {
           
                success(msg)
                sessionStorage.setItem('token', '123456')
                sessionStorage.setItem('user_id', user_id)
                let account = username
                storage.set('selfInfo', copy)
       
                socket.emit('reqLatestPrivateHistory', account)
                socket.emit('saveSocketId', { account })
                nav('/yinmeng')
                // window.location.reload()
            } else {
                error(msg)
            }
        }
    }
    //跳转注册界面
    const zhu = () => {
        nav('/regist')
    }
    //用户名和密码的表单
    function Fromm() {
        return <Form
            className='login-form'
            layout='horizontal'
            footer={
                <span>


                    <a style={{ fontSize: '12px', marginRight: '2.5rem' }} onClick={login}>试一下人脸登录？</a>
                    <a style={{ marginTop: '20px', fontSize: '12px' }} onClick={zhu}>没有账号，注册一个？</a>
                    <button  id='button' block type='submit' color='primary' size='large' style={{ marginTop: '10px' }} onClick={() => { login1() }}>
                        登录
                    </button>
                </span>
            }
        >

            <Form.Item
                name='name'
                label='用户名'
                rules={[{ required: true, message: '请输入用户名' }]}
            >
                <Input onChange={(e) => { setname(e); }} placeholder='请输入用户名' />
            </Form.Item>
            <Form.Item
                name='password'
                label='密码'
                rules={[{ required: true, message: '请输入密码' }]}
            >
                <Input onChange={(e) => { setpassword(e); }} placeholder='请输入密码' type='password'/>
            </Form.Item>
        </Form>
    }
    return (
        <div className='box1 animate__animated animate__bounce'>

            {contextHolder}


            {/* 
      人脸识别登录
      */}
            <div className='shi'>
                <div style={{ color: 'theme.tc2', fontSize: 22 }}>
                    {/* {!faceCheck ? '人脸登录' : '认证失败，请重试'} */}
                </div>
                <video
                    width='200px'
                    height='200px'
                    autoPlay
                    ref={videoRef}
                ></video>
                <canvas
                    ref={canvasRef}
                    width='400px'
                    height='400px'
                    style={{ display: 'none' }}
                ></canvas>
                <img
                    ref={imageRef}
                    src=''
                    alt='人脸识别'
                    style={{ display: 'none' }}
                />
                {faceCheck ? (
                    <div
                        style={{
                            position: 'absolute',
                            top: 105,
                            left: 20,
                            height: 100,
                            width: 100,
                            background: '#fff',
                            display: 'flex',
                            justifyContent: 'center',
                            flexDirection: 'column',
                            alignItems: 'center',
                        }}
                    >
                        <button
                            type='primary'
                            style={{
                                fontSize: 14,
                                width: 120,
                                marginBottom: 15,
                                // background:'transparent',
                                border:'none',
                                outline:'none',
                            }}
                            onClick={() => {
                                setFaceCheck(false)
                                openMedia()
                                getPhotoUrl()
                            }}
                        >
                            继续人脸识别
                        </button>
                    </div>
                ) : (
                    ''
                )}
            </div>
            {/*
           用户密码表单验证
           */}
            {Fromm()}


        </div>
    )
}




